package com.qjc.config;

/**
 * @ClassName: LocalDateTimeTypeHandler
 * @Description:
 * @Author: qiaojiacheng
 * @Date: 2021/3/25 5:47 下午
 */

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @ClassName: LocalDateTimeTypeHandler
 * @Description: 用来解决shardingSphere-jdbc不支持LocalDateTime的问题
 * @Author: qiaojiacheng
 * @Date: 2021/3/25 6:34 下午
 */
@Component
/**
 * 定义转换器支持的JAVA类型
 */
@MappedTypes(LocalDateTime.class)
/**
 * 定义转换器支持的数据库类型
 */
@MappedJdbcTypes(value = JdbcType.TIMESTAMP, includeNullJdbcType = true)
public class LocalDateTimeTypeHandler extends BaseTypeHandler<LocalDateTime> {

    private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, LocalDateTime parameter, JdbcType jdbcType)
            throws SQLException {
        if (parameter != null) {
            ps.setString(i, dateTimeFormatter.format(parameter));
        }
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String target = rs.getString(columnName);
        if (StringUtils.isEmpty(target)) {
            return null;
        }
        return DateUtil.toLocalDateTime(DateUtil.parseDateTime(target));
    }

    @Override
    public LocalDateTime getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String target = rs.getString(columnIndex);
        if (StringUtils.isEmpty(target)) {
            return null;
        }
        return DateUtil.toLocalDateTime(DateUtil.parseDateTime(target));
    }

    @Override
    public LocalDateTime getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String target = cs.getString(columnIndex);
        if (StringUtils.isEmpty(target)) {
            return null;
        }
        return DateUtil.toLocalDateTime(DateUtil.parseDateTime(target));
    }
}
